<template>
  <div class="payment-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar fixed title="订单信息" left-arrow @click-left="goBack" />
    <van-form @submit="onSubmit" title="Billing Address">
      <van-cell-group>
        <div class="card-type">
          <van-dropdown-menu style="flex: 1;">
            <van-dropdown-item :title="'卡类型：'+ order.cardType" v-model="order.cardType" :options="cardType" />
          </van-dropdown-menu>
        </div>
        <van-field
            v-model="order.creditCard"
            name="creditCard"
            label="卡号"
            :rules="[{ required: true, message: '请输入有效卡号' }]"
        />
        <van-field
            v-model="order.expiryDate"
            name="expiryDate"
            label="有效期限"
            placeholder="MM/YYYY"
            :rules="[{ required: true, message: '请输入有效期限' }]"
        />
      </van-cell-group>
      <van-collapse v-model="activeNames">
        <van-collapse-item title="账单地址" name="1">
          <van-cell-group inset>
            <van-field v-model="order.billToFirstName" label="名"/>
            <van-field v-model="order.billToLastName" label="姓"/>
            <van-field v-model="order.billAddress1" label="地址1"/>
            <van-field v-model="order.billAddress2" label="地址2"/>
            <van-field v-model="order.billCity" label="城市"/>
            <van-field v-model="order.billState" label="州/省"/>
            <van-field v-model="order.billZip" label="邮政编码"/>
            <van-field v-model="order.billCountry" label="国家"/>
          </van-cell-group>
        </van-collapse-item>
      </van-collapse>
      <!-- 支付 -->
      <div class="payment-button" style="margin: 16px;">
        <van-button color="#f9bd10" round block type="primary" native-type="submit" @click="onSubmit">
          <span style="font-weight: 700;">支付</span>
        </van-button>
      </div>
    </van-form>

    <!-- 弹窗 -->
    <div class="change-address-button"  style="margin: 16px;">
      <van-button color="#FFDF76" round block @click=" backupOrder">
        <span style="font-weight: 700;">修改送货地址</span>
      </van-button>
    </div>
    <van-dialog
        v-model:show="showShipTo"
        title="送货到另一地址"
        show-cancel-button confirm-button-text="修改"
        @cancel="cancelChange"
    >
      <van-cell-group>
        <van-field v-model="order.shipToFirstName" label="名"/>
        <van-field v-model="order.shipToLastName" label="姓"/>
        <van-field v-model="order.shipAddress1" label="地址1"/>
        <van-field v-model="order.shipAddress2" label="地址2"/>
        <van-field v-model="order.shipCity" label="城市"/>
        <van-field v-model="order.shipState" label="州/省"/>
        <van-field v-model="order.shipZip" label="邮政编码"/>
        <van-field v-model="order.shipCountry" label="国家"/>
      </van-cell-group>
    </van-dialog>
    <van-dialog
        v-model:show="showConfirmOrder"
        title="订单"
        show-cancel-button
        confirm-button-text="确定"
        @confirm="confirmOrder"
    >
      <div class="scrollable-content">
        <van-cell-group title="支付信息" inset>
          <p>卡类型: {{ order.cardType }}</p>
          <p>卡号: {{ order.creditCard }}</p>
          <p>有效期限: {{ order.expiryDate }}</p>
        </van-cell-group>
        <van-cell-group title="账单地址" inset>
          <p>名: {{ order.billToFirstName }}</p>
          <p>姓: {{ order.billToLastName }}</p>
          <p>地址1: {{ order.billAddress1 }}</p>
          <p>地址2: {{ order.billAddress2 }}</p>
          <p>城市: {{ order.billCity }}</p>
          <p>州/省: {{ order.billState }}</p>
          <p>邮政编码: {{ order.billZip }}</p>
          <p>国家: {{ order.billCountry }}</p>
        </van-cell-group>
        <van-cell-group title="送货地址"  inset>
          <p>名: {{ order.shipToFirstName }}</p>
          <p>姓: {{ order.shipToLastName }}</p>
          <p>地址1: {{ order.shipAddress1 }}</p>
          <p>地址2: {{ order.shipAddress2 }}</p>
          <p>城市: {{ order.shipCity }}</p>
          <p>州/省: {{ order.shipState }}</p>
          <p>邮政编码: {{ order.shipZip }}</p>
          <p>国家: {{ order.shipCountry }}</p>
        </van-cell-group>
        <van-cell-group v-for="(item, index) in cartItems" :key="index" :title="index+1" class="cart-item"  inset>
          <p>商品ID: {{ item.itemId}}</p>
          <p>数量: {{ item.quantity }}</p>
          <p>单价: {{ item.listPrice }}</p>
        </van-cell-group>
        <van-cell-group>
          <van-cell title="总费用:" :value="totalPrice"  />
        </van-cell-group>
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import {createOrderService} from "@/api/order.js";
import {getCartItemListService} from "@/api/cart.js";
import router from "@/router/index.js";
import { useRouter} from "vue-router";
import {userGetProfileService} from "@/api/user.js";
import { getCartList } from '@/utils/storage';

// 弹窗展示
const showShipTo = ref(false);
const showConfirmOrder= ref(false);

// 备份订单数据
const orderBackup = {};

const cardType = ref([
  { text: 'VISA', value: 'VISA' },
  { text: '万事达', value: '万事达' },
  { text: '美国运通', value: '美国运通' },
]);
const activeNames = ref(['1']);
const totalPrice = ref(0);

const order = ref({
  username: '',
  cardType: '万事达',
  creditCard: '52713524856122',
  expiryDate: '12/2026',
  billToFirstName: '',
  billToLastName: '',
  billAddress1: '',
  billAddress2: '',
  billCity: '',
  billState: '',
  billZip: '',
  billCountry: '',
  shipToFirstName: '',
  shipToLastName: '',
  shipAddress1: '',
  shipAddress2: '',
  shipCity: '',
  shipState: '',
  shipZip: '',
  shipCountry: '',
  courier: 'UPS',
  locale: 'CA',
  totalPrice: 0,
  lineItems: [{
    lineNum: 0,
    itemId: '',
    quantity: 0,
    listPrice: '',
    totalCost: ''
  }],
}
);

const cartItems=ref([
  {
    id: 0,
    itemId: 0,
    productId: '商品名称',
    listPrice: '0',
    unitCost: '0.00',
    supplierId: '0',
    status: '状态',
    description: '描述',
    image: 'product.jpg',
    quantity: 1,
    checked: false
  }
])

// 备份订单数据的方法
const backupOrder = () => {
  orderBackup.value = { ...order.value };
  showShipTo.value = true;
};

//填充订单
const fillOrder = async () => {
  try {
    // 获取用户信息
    const result1 = await userGetProfileService();
    const userInfo = result1.data.data;
    order.value.billToFirstName = userInfo.firstName;
    order.value.billToLastName = userInfo.lastName;
    order.value.billAddress1 = userInfo.address1;
    order.value.billAddress2 = userInfo.address2;
    order.value.billCity = userInfo.city;
    order.value.billState = userInfo.state;
    order.value.billZip = userInfo.zip;
    order.value.billCountry = userInfo.country;
    order.value.shipToFirstName = userInfo.firstName;
    order.value.shipToLastName = userInfo.lastName;
    order.value.shipAddress1 = userInfo.address1;
    order.value.shipAddress2 = userInfo.address2;
    order.value.shipCity = userInfo.city;
    order.value.shipState = userInfo.state;
    order.value.shipZip = userInfo.zip;
    order.value.shipCountry = userInfo.country;
    cartItems.value = getCartList();  //获取购物车选中信息

    // 计算购物车商品总价值
    console.log(cartItems.value);
    for (let i = 0; i < cartItems.value.length; i++) {

    }
    cartItems.value.forEach(item => {
      totalPrice.value += Number(item.listPrice) * parseInt(item.quantity);
    });
    // 将总价值填入订单信息
    order.value.totalPrice = totalPrice.value;
    console.log(order.value);
  } catch (error) {
    console.error('Error filling order:', error);
  }
}

// 点击取消按钮执行的方法
const cancelChange = () => {
  // 关闭弹窗并恢复原始地址信息
  showShipTo.value = false;
  // 恢复备份的订单数据
  order.value = { ...orderBackup.value };
};

const goBack = async () => {
  try {
    // 将备份数据重新添加到后端购物车中
    //await Promise.all(uncheckedItems.value.map(item => addCartItemService(item.id)));
    // 返回上一页的操作
    router.go(-1);
  } catch (error) {
    console.error('恢复购物车失败:', error);
    // 处理恢复购物车失败的情况
  }
};

const confirmOrder = async () => {
  order.value.lineItems = cartItems.value;
  //上传订单
  await createOrderService(order.value);
  showToast({
          message: `<div style="height:22px;display:flex;justify-content: center;align-items: center;user-select:none;"><i class="van-icon van-icon-success" style="font-size:16px;margin-right:5px"></i><span>生成订单成功</span></div>`,
          type: 'html'
        });
  // 返回到主页面
  router.push('/home');
};

//显示确认弹窗
const onSubmit=()=>{
  //显示弹窗
  showConfirmOrder.value = true;
}

onMounted(() => {
  fillOrder();
  console.log(`the component is now mounted.`)
})
</script>


<style scoped>
.payment-page {
  margin-top: 40px; /* 留出标题栏高度的空间 */
  padding-bottom: 12%;
  ::v-deep .van-icon-arrow-left {
    color: #333;
  }
}

.form-container {
  padding-top: 40px; /* 确保表单内容不被标题栏遮挡 */
}
.payment-page {
  height: 100%;
  background-color: #fff;
}

/* 修改主题颜色 */
.van-nav-bar__title,
.van-nav-bar__text {
  color: #fff;
}

.van-nav-bar__left {
  color: #fff;
}

.van-field__label {
  color: #000;
}

.van-button--info {
  background-color: #FFDF75;
}

.van-nav-bar {
  background-color: #FFDF75;
}
.payment-button {
  position: fixed;
  bottom: -10px; /* 调整按钮到底部的距离 */
  left: 52%; /* 调整按钮距离左侧的位置 */
  width: 40%;
  z-index: 99;
  height: 50px; /* 增大按钮高度 */
  line-height: 50px; /* 让文字在按钮中垂直居中 */
  text-align: center; /* 文字居中 *
  border-radius: 8px; /* 添加圆角 */
}
.custom-field .van-field__control {
  width: 100%; /* 设置输入框宽度与下拉框一致 */
}

.custom-field .van-dropdown-menu__content {
  box-shadow: none; /* 去除下拉框的突出样式 */
}
.change-address-button{
  position: fixed;
  bottom: -10px; /* 调整按钮到底部的距离 */
  left: 0; /* 调整按钮距离左侧的位置 */
  width: 40%;
  z-index: 99;
  height: 50px; /* 增大按钮高度 */
  line-height: 50px; /* 让文字在按钮中垂直居中 */
  text-align: center; /* 文字居中 */
  border-radius: 8px; /* 添加圆角 */
}
.scrollable-content {
  max-height: 60vh; /* Adjust the maximum height as needed */
  overflow-y: auto;
  text-align: left;
}

</style>



